package complexity;

import java.util.Iterator;

public class Stack<T> implements Iterable<T>{
    private Node head;
    private int N;
    public Stack() {
        this.head=new Node(null,null);
        this.N=0;
    }
    public T pop(){
        Node oldNode = head.next;
        if (oldNode==null){
            return null;
        }
        head.next=oldNode.next;
        this.N--;
        return oldNode.data;
    }
    public boolean isEmpty(){
        return this.N==0;
    }
    public int size(){
        return this.N;
    }
    public void push(T t){
        //找到首节点指向的第一个节点
        Node oldFirst = head.next;
        Node newNode = new Node(null, t);
        //创建新节点
        //让首节点指向新节点
        head.next=newNode;
        //让新节点指向原来的第一个节点
        newNode.next=oldFirst;
        this.N++;
    }
    @Override
    public Iterator<T> iterator() {
        return new IStack();
    }
    private class IStack implements Iterator {
        private Node node;
        //定义一个节点
        public IStack() {
            //构造函数初始化
            this.node=head;
        }
        @Override
        public boolean hasNext() {
            //判断当前节点是否为空
            return node.next!=null;
        }
        @Override
        public T next() {
            //下一节点返回给node
            node = node.next;
            //返回下一节点的数据
            return node.data;
        }
    }
    private class Node{
        private Node next;
        private T data;
        public Node(Node next, T data) {
            this.next = next;
            this.data = data;
        }
    }
}
